package com.chenx.ps_server;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {
    private TextView mTextMessage;
    private ImageView img;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    img.setVisibility(View.GONE);
                    mTextMessage.setVisibility(View.VISIBLE);
                    mTextMessage.setText("1.手机设置-》开启wifi热点-》PS连上wifi\n2.点击服务器按钮重新获取ip\n3.浏览器打开:"+getIp());
                  //  mTextMessage.setText("服务器");
                    return true;
                case R.id.navigation_dashboard:
                    img.setVisibility(View.VISIBLE);
                    mTextMessage.setVisibility(View.GONE);
                  //  mTextMessage.setText("赞赏码");
                    return true;
                case R.id.navigation_notifications:
                    img.setVisibility(View.GONE);
                    mTextMessage.setVisibility(View.VISIBLE);
                    mTextMessage.setText("chenx");
                  //  mTextMessage.setText("作者");
                    return true;
            }
            return false;
        }
    };
    public static final int EXTERNAL_STORAGE_REQ_CODE = 10 ;
    SimpleServer server;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        mTextMessage = findViewById(R.id.message);

        img=findViewById(R.id.img);
        navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);


        int permission = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);


        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                EXTERNAL_STORAGE_REQ_CODE);
         }


        // 把assets中的h5.zip拷贝到sd上，并解压此zip
      //  String baseDir = FileUtils.isSDCardAvailable() ? FileUtils.getExternalStoragePath() : FileUtils.getCachePath(this);
       String locationZip  = Environment.getExternalStorageDirectory().toString() +"/ps4/ps4.zip";;
        try {
           // BaseFileUtil.createFile(locationZip);

            BaseFileUtil.createFile(locationZip);

            InputStream in = this.getResources().openRawResource(R.raw.ps4);

            BaseFileUtil.copyBigDataToSD(this, locationZip, in);
            BaseFileUtil.upZipFile(new File(locationZip), Environment.getExternalStorageDirectory().toString() +"/ps4/");
        } catch (Exception e) {
            e.printStackTrace();
            //BaseFileUtil.delFile(baseDir + IntentTAG.LOCATION_H5_BASE_PATH); // 解压失败，删除此文件夹下所有文件
        }


      // TextView t= findViewById(R.id.message);


        server = new SimpleServer();
        try {
            server.start();
            //Log.i("Httpd",Server startup);
        } catch(IOException ioe) {
           // Log.w("Httpd",server startup failed);
            Toast.makeText(getApplicationContext(),ioe.getMessage().toString(),Toast.LENGTH_SHORT).show();
        }
        img.setVisibility(View.GONE);
        mTextMessage.setVisibility(View.VISIBLE);
        mTextMessage.setText("1.手机设置-》开启wifi热点-》PS连上wifi\n2.点击服务器按钮重新获取ip\n3.浏览器打开:"+getIp());
    }


    public static String getIp() {
        String s="";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface iface = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = iface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        if (inetAddress.getHostAddress().contains("43."))
                        { s="http://"+inetAddress.getHostAddress()+":1234"; break;}

                    }
                }
            }
            return s;
        } catch (SocketException ignored) {
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (server != null){
            server.stop();
        }
//        Log.w("Httpd", "The server stopped.");
    }

}
